package com.dingwen.stusprbooes.dao;

import com.dingwen.stusprbooes.constant.ElasticsearchConstant;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.blobstore.DeleteResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * base dao
 *
 * @author dingwen
 * 2021/6/27 20:58
 **/

@Repository
public class IndexDao {

    private final RestHighLevelClient restHighLevelClient;

    @Autowired
    public IndexDao(RestHighLevelClient restHighLevelClient) {
        this.restHighLevelClient = restHighLevelClient;
    }


    /**
     * 保存
     *
     * @param index 指数
     * @return {@link CreateIndexResponse}
     * @throws IOException io exception
     */
    public CreateIndexResponse create(String index) throws IOException {
        // 创建索引请求
        CreateIndexRequest request = new CreateIndexRequest(ElasticsearchConstant.INDEX);
        return restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
    }


    /**
     * 索引是否存在
     *
     * @param index 指数
     * @return boolean
     */
    public boolean exists(String index) throws IOException {
        GetIndexRequest request = new GetIndexRequest(index);
        return restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
    }


    /**
     * 删除
     *
     * @param index 指数
     * @return {@link AcknowledgedResponse}
     * @throws IOException io exception
     */
    public AcknowledgedResponse remove(String index) throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest(index);
        return restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
    }



}
